<template>
  <div>
    <el-form :inline="true" :model="searchMap" class="demo-form-inline">
      <el-form-item label="品牌编号">
        <el-input v-model="searchMap.id" placeholder="请输入品牌编号"></el-input>
      </el-form-item>
      <el-form-item label="品牌名称">
        <el-input v-model="searchMap.name" placeholder="请输入品牌名称"></el-input>
      </el-form-item>
      <el-form-item label="首字母">
        <el-input v-model="searchMap.letter" placeholder="请输入品牌首字母"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button type="primary" @click="dialogFormVisible=true; brandForm={}; imageUrl=''">新增品牌</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column label="编号" width="180" prop="id"></el-table-column>
      <el-table-column label="品牌名称" width="180" prop="name"></el-table-column>
      <el-table-column label="首字母" width="180" prop="letter"></el-table-column>
      <el-table-column label="品牌图片" width="180">
        <template slot-scope="scope">
          <img :src="scope.row.image" width="160px" height="80px" />
        </template>
      </el-table-column>
      <el-table-column label="排序" width="180" prop="seq"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row);">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="pageSizeList"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>

    <el-dialog :title="brandForm.id==null?'新增':'编辑'" :visible.sync="dialogFormVisible">
      <el-form :model="brandForm">
        <el-form-item label="品牌名称" :label-width="formLabelWidth">
          <el-input v-model="brandForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="品牌图片" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:88/api/oss/upload/oss?folder=myimages&classify=brand"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="首字母" :label-width="formLabelWidth">
          <el-input v-model="brandForm.letter" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="排序" :label-width="formLabelWidth">
          <el-input v-model="brandForm.seq" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="分类" :label-width="formLabelWidth">
          <el-select v-model="value1" placeholder="请选择一级分类" @change="selectChange1">
        <el-option v-for="item in options1" :key="item.id" :label="item.name" :value="item.id"></el-option>
      </el-select>

      <el-select
        v-model="value2"
        collapse-tags
        style="margin-left: 20px;"
        placeholder="请选择二级分类"
        @change="selectChange2"
      >
        <el-option v-for="item in options2" :key="item.value" :label="item.name" :value="item.id"></el-option>
      </el-select>

      <el-select
        v-model="value3"
        collapse-tags
        style="margin-left: 20px;"
        placeholder="请选择三级分类"
        @change="selectChange3"
      >
        <el-option v-for="item in options3" :key="item.value" :label="item.name" :value="item.id"></el-option>
      </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false; brandForm={}">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      options1: [],
      options2: [],
      options3: [],
      value1: [],
      value2: [],
      value3: [],
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      pageSizeList: [5, 10, 20, 30],
      total: 0,
      searchMap: {},
      dialogFormVisible: false,
      brandForm: {},
      xian: {},
      formLabelWidth: "150px",
      imageUrl: "",
      categoryId: '',
      parentId: 0,
      objs: [], // 存储id 跟name
      id1: 0,
      id2: [],
      id3: [],
      data: this.object
    };
  },
  methods: {
    async getBrandList () {
      console.log(this.searchMap)
      const { data: res } = await this.$http.post(
        `goods/brand/findPage/${this.currentPage}/${this.pageSize}`,
        this.searchMap
      );
      this.tableData = res.data.rows;
      this.total = res.data.total;
    },
    onSubmit () {
      this.currentPage = 1;
      this.getBrandList();
    },
    async handleEdit (index, row) {
      this.dialogFormVisible = true;
      const id = row.id;
      const { data: res } = await this.$http.get(`goods/brand/findById/${id}`);
      this.brandForm = res.data;
      this.imageUrl = this.brandForm.image
      this.brandForm.id = id
    },
    async handleDelete (index, row) {
      const id = row.id;
      this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const str = row.image.split("/")
          console.log(str[2])
          if (str[2] === 'w-xian.oss-cn-hangzhou.aliyuncs.com') {
            console.log(row.image)
            this.$http.post(`http://localhost:88/api/oss/upload/ossDelete?fileName=${row.image}`)
          }
          const { data: res } = await this.$http.post(`goods/brand/delete/${id}`);
          if (res.code === 200) {
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            this.getBrandList();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    async handleSizeChange (val) {
      this.pageSize = val;
      this.getBrandList();
    },
    async handleCurrentChange (val) {
      this.currentPage = val;
      this.getBrandList();
    },
    async save () {
      this.brandForm.image = this.imageUrl
      this.dialogFormVisible = false;
      console.log(this.brandForm)
      console.log(this.parentId)
      const { data: res } = await this.$http.post(
        `goods/brand/${this.brandForm.id == null ? "insert" : "update"}/${this.parentId}`,
        this.brandForm
      );
      if (res.code === 200) {
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        this.getBrandList();
      }
    },
    async dd () {
      const { data: res } = await this.$http.get(
        `goods/brand/page?page=${this.currentPage}&size=${this.pageSize}`
      );
      console.log(res);
      this.xian = res.data.list;
      // 集合转数组
      // for (var i in this.xian) {
      //   this.tableData.push(this.xian[i])
      // }
      this.tableData = Object.values(this.xian);
      this.total = res.data.total;
    },
    handleAvatarSuccess (res, file) {
      this.imageUrl = file.response;
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    async selectChange1 () {
      // 从别的页面过来回显过先清空 数组
      if (this.objs.length >= 3) {
        this.objs = []
      }
      if (this.objs !== undefined && this.objs.length > 0) {
        for (let i = 0; i < this.objs.length; i++) {
          if (this.objs[i].id === this.id) {
            this.id = this.value1
            this.objs.splice(i, 3);
          }
        }
      } else {
        this.id = this.value1
      }
      this.value2 = ''
      this.value3 = ''
      this.parentId = this.value1
      const { data: res } = await this.$http.get(`goods/category/selectParentId?parentId=${this.parentId}`)
      this.options2 = res.data
    },
    // 第二个下拉框选中的操作
    async selectChange2 () {
      if (this.objs !== undefined && this.objs.length > 0) {
        if (this.objs.length > 1) {
          for (let i = 0; i < this.objs.length; i++) {
            if (this.objs[i].id === this.id2) {
              this.id2 = this.value2
              this.objs.splice(i, 2);
            }
          }
        } else {
          this.id2 = this.value2
        }
      }
      this.value3 = ''
      this.parentId = this.value2
      const { data: res } = await this.$http.get(`goods/category/selectParentId?parentId=${this.parentId}`)
      this.options3 = res.data
    },
    // 第三个下拉框选中的操作
    async selectChange3 () {
      if (this.objs !== undefined && this.objs.length > 0) {
        if (this.objs.length > 2) {
          for (let i = 0; i < this.objs.length; i++) {
            if (this.objs[i].id === this.id3) {
              this.id3 = this.value3
              this.objs.splice(i, 1);
            }
          }
        } else {
          this.id3 = this.value3
        }
      }
      this.parentId = this.value3
      console.log(this.parentId)
    }
  },
  async created () {
    const { data: res } = await this.$http.get(`goods/category/selectParentId?parentId=${this.parentId}`)
    this.options1 = res.data
    this.getBrandList();
  }
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 250px;
  height: 178px;
  display: block;
}
</style>
